package com.skcc.ngms.matest;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.skcc.alopex.common.activity.MainActivity;
import com.skcc.alopex.common.extension.NativeUIInterface;

public class GmpAuth implements NativeUIInterface {

	private MainActivity mActivity = MainActivity.mInstance;
	private String successCallback; 
	private String errorCallback;
	
	public void loginGmp(String successCallback, String errorCallback) {
		mActivity.setNativeUIInterface(this);
		
		this.successCallback = successCallback;
		this.errorCallback = errorCallback;
		
		AuthUtil.runGMPLogin(mActivity);
	}
	
	public void writeFile(String fileName, String content){
		try {
			byte[] decode = Base64Encoder.decode(content);
			fileWrite(fileName, decode);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void fileWrite(String fileName, byte[] buffer) {
		FileOutputStream out = null;

		try {
			out = new FileOutputStream("/sdcard/"+fileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		for (int i = 0; i < buffer.length; i++) {
			try {
				out.write(buffer[i]);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		try {
			out.close();
			Toast.makeText(mActivity, "SDCARD에 저장되었습니다.", 0).show();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void getAuthInfo(String successCallback, String errorCallback){
		try {
			AuthUtil.GMPAuth(mActivity);
			String temp = AuthUtil.AUTH_INFO;
			
			Log.i("Auth Info..", temp);
			mActivity.loadUrl("javascript:" + successCallback + "('"+temp+"');");
		} catch (Exception e) {
			mActivity.loadUrl("javascript:" + errorCallback + "(\"AuthError\");");
			e.printStackTrace();
		}
	}

	public void logoutGmp(String successCallback, String errorCallback){
		
		this.successCallback = successCallback;
		this.errorCallback = errorCallback;
		
		try {
			AuthUtil.logout(mActivity);
			mActivity.loadUrl("javascript:" + successCallback + "(\"logout Success\");");
		} catch (Exception e) {
			mActivity.loadUrl("javascript:" + errorCallback + "(\"logout error\");");
			e.printStackTrace();
		}
	}

	public void doWorkOnUIMainThread(int arg0, Bundle arg1) {
		// TODO Auto-generated method stub

	}

	public void onResultBack(Intent arg0, int arg1) {
		try {
			Log.e("GMPTest", "In onResultBack");
			Log.e("GMPTest", successCallback);
			AuthUtil.GMPAuth(mActivity);
			mActivity.loadUrl("javascript:" + successCallback + "('"+AuthUtil.AUTH_INFO+"');");
		} catch (Exception e) {
			mActivity.loadUrl("javascript:" + errorCallback + "(\"login error\");");
			e.printStackTrace();
		}
		
	}
	public void getRegistraionId(String successCallback, String errorCallback){
		try{
			mActivity.loadUrl("javascript:" + successCallback + "('"+C2dm_BroadcastReceiver.registration_id+"');");
		} catch (Exception e) {
			mActivity.loadUrl("javascript:" + errorCallback + "(\"Provision Error\");");
			e.printStackTrace();
		}
	}
	
	public void provision(String successCallback, String errorCallback) throws Exception{
		//C2DM 등록ID 발급
		Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
		registrationIntent.putExtra("app", PendingIntent.getBroadcast(mActivity.getBaseContext(), 0, new Intent(), 0)); // 어플리케이션ID
		registrationIntent.putExtra("sender", "chsyong2@gmail.com"); //개발자ID
		mActivity.startService(registrationIntent); //서비스 시작(등록ID발급받기)
		
		String authToken = getAuthToken();
		try{
			mActivity.loadUrl("javascript:" + successCallback + "('" + C2dm_BroadcastReceiver.registration_id + "', '" + authToken + "');");// "(\"Provision Success\");");
		} catch (Exception e) {
			mActivity.loadUrl("javascript:" + errorCallback + "(\"Provision Error\");");
			e.printStackTrace();
		}
	
//		sender(C2dm_BroadcastReceiver.registration_id,getAuthToken(),msg_text.getText().toString());
	}
	
	 public String getAuthToken() throws Exception{
	    	String authtoken = "";
	        
	    	StringBuffer postDataBuilder = new StringBuffer();
	        postDataBuilder.append("accountType=HOSTED_OR_GOOGLE"); //똑같이 써주셔야 합니다.
	        postDataBuilder.append("&Email=chsyong2@gmail.com");  //개발자 구글 id
	        postDataBuilder.append("&Passwd=jpjg8351");	          //개발자 구글 비빌번호
	        postDataBuilder.append("&service=ac2dm");						
	        postDataBuilder.append("&source=test-1.0");

	        byte[] postData = postDataBuilder.toString().getBytes("UTF8");

	        URL url = new URL("https://www.google.com/accounts/ClientLogin");
	        
	        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	        conn.setDoOutput(true);
	        conn.setUseCaches(false);
	        conn.setRequestMethod("POST");
	        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	        conn.setRequestProperty("Content-Length", Integer.toString(postData.length));

	        
	        OutputStream out = conn.getOutputStream();
	        out.write(postData);
	        out.close();

	        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	        
	        String sidLine = br.readLine();
	        String lsidLine = br.readLine();
	        String authLine = br.readLine();
	        
	        System.out.println("sidLine----------->>>"+sidLine);
	        System.out.println("lsidLine----------->>>"+lsidLine);
	        System.out.println("authLine----------->>>"+authLine);
	        System.out.println("AuthKey----------->>>"+authLine.substring(5, authLine.length()));
	        
	        authtoken = authLine.substring(5, authLine.length());
	        
	     return authtoken;
	    }
}
